import { MessageType, StateType, CollectState } from '@/config';
import {
  getGigaProductDetailInfo,
  getGigaProductInfo as getGigaProductInfoUtil,
  getGigaResource,
} from '@/lib/giga';
import { useSettingsStore } from '@/store';
import { OperationMessageType } from '@/store/message';
import { toast } from 'sonner';
import { useSave } from '../../hook/useSave';
import { useMessage } from './useGigaMessage';
import { useDirectoryHandle } from '@/entrypoints/hook/useDirectoryHandle';
import { TaskInfo } from '@/entrypoints/hook/useConcurrentRequest';
import { getProductState, setProductState } from '@/lib/filesystem';

const collectingProduct: Record<string, boolean> = {};
export function useGiga() {
  const minAvailable = useSettingsStore((state) => state.gigaSettings.minAvailable);
  const { resetMessage, addMessage, resetAndAddMessage } = useMessage();
  const { saveGigaResource, saveGigaDetailInfo } = useSave({
    addMessage,
  });
  const appConfig = useAppConfig();
  const { getDirectoryHandle } = useDirectoryHandle();

  const getAndSaveGigaDetailResource = useCallback(
    async function getAndSaveGigaDetailResource(
      skuIdInfo: string,
      gigaProductId: string,
      skuIdInfoDirectoryHandle: FileSystemDirectoryHandle,
    ) {
      addMessage({
        category: skuIdInfo,
        type: OperationMessageType.info,
        message: `开始下载 giga 中的资源包(需要等待一定的时间)`,
      });
      const blob = await getGigaResource(gigaProductId);
      // console.log(zipBlobResult);
      addMessage({
        category: skuIdInfo,
        type: OperationMessageType.success,
        message: `成功获取资源包`,
      });
      await saveGigaResource({
        blob,
        skuIdInfo,
        directoryHandle: skuIdInfoDirectoryHandle,
        filterImage: true,
      });
      addMessage({
        category: skuIdInfo,
        type: OperationMessageType.success,
        message: `成功把资源保存到货号目录下`,
      });
    },
    [saveGigaResource],
  );

  const createSkuIdInfoDirectoryHandle = useCallback(
    async function createSkuIdInfoDirectoryHandle(skuIdInfo: string) {
      const directoryHandle = await getDirectoryHandle();
      const skuIdInfoDirectoryHandle = await directoryHandle.getDirectoryHandle(skuIdInfo, {
        create: true,
      });
      return skuIdInfoDirectoryHandle;
    },
    [getDirectoryHandle],
  );

  const getAndSaveGigaProductInfo = useCallback(
    async function getAndSaveGigaProductInfo({
      gigaProductId,
      gigaSku,
      skuIdInfo,
      skuIdInfoDirectoryHandle,
    }: {
      gigaProductId: string;
      gigaSku: string;
      skuIdInfo: string;
      skuIdInfoDirectoryHandle: FileSystemDirectoryHandle;
    }) {
      addMessage({
        category: skuIdInfo,
        type: OperationMessageType.info,
        message: `开始获取 giga 的详细信息`,
      });

      // 读取详细的信息并进行整理
      const gigaProductDetailInfo = await getGigaProductDetailInfo({
        gigaProductId,
        gigaSku,
        skuIdInfo,
      });
      console.log('giga 的详细信息:', gigaProductDetailInfo);
      addMessage({
        category: skuIdInfo,
        type: OperationMessageType.success,
        message: `获取 giga 的详细信息成功`,
        data: {
          data: gigaProductDetailInfo,
          kind: 'GIGA 产品信息',
        },
      });

      if (gigaProductDetailInfo.available < minAvailable) {
        throw new Error(`产品库存为 ${gigaProductDetailInfo.available},小于最小可采集库存`);
      }

      await saveGigaDetailInfo({
        gigaProductDetailInfo,
        skuIdInfoDirectoryHandle,
      });

      addMessage({
        category: skuIdInfo,
        type: OperationMessageType.success,
        message: `成功保存 giga 的详细信息到 ${appConfig.gigaProductDetailInfoFilename} 文件下`,
      });
    },
    [minAvailable, saveGigaDetailInfo, appConfig],
  );

  const collectGigaProduct = useCallback(
    async function collectGigaProduct({
      skuIdInfo,
      gigaProductId,
      gigaSku,
      available,
      force = false,
    }: TaskInfo) {
      // console.log('采集参数', available, minAvailable);

      // 如果商品正在采集,那么提出提示不会做任何事情
      if (collectingProduct[skuIdInfo]) {
        toast.info(`货号 ${skuIdInfo} 正在采集中`);
        return;
      }

      collectingProduct[skuIdInfo] = true;

      // 创建货号目录
      const skuIdInfoDirectoryHandle = await createSkuIdInfoDirectoryHandle(skuIdInfo).catch(
        (error) => {
          collectingProduct[skuIdInfo] = false;
          throw error;
        },
      );
      try {
        resetAndAddMessage({
          type: OperationMessageType.info,
          category: skuIdInfo,
          message: '开始采集产品信息',
        });
        toast.info(`${skuIdInfo}: 采集开始`);
        if (available !== undefined && available < minAvailable) {
          throw new Error(`产品库存为 ${available},小于最小可采集库存`);
        }

        if (!force) {
          const state = await getProductState(
            appConfig.productStateFilename,
            skuIdInfoDirectoryHandle,
          );
          if (state.collectState === CollectState.success) {
            addMessage({
              category: skuIdInfo,
              type: OperationMessageType.success,
              message: `该产品已经采集过了 ${doneMessage}`,
            });
            toast.success(`${skuIdInfo}: 已经采集过了`);
            collectingProduct[skuIdInfo] = false;
            return;
          }
        }

        // 读取产品的详细信息, 并整理后保存到 gigaProduct.json 文件中
        await getAndSaveGigaProductInfo({
          gigaProductId,
          gigaSku,
          skuIdInfo,
          skuIdInfoDirectoryHandle,
        });

        // 读取产品的资源信息,并生成对应的目录
        // 无法并行,因为要获取库存信息
        await getAndSaveGigaDetailResource(skuIdInfo, gigaProductId, skuIdInfoDirectoryHandle);

        // 创建采集完成的状态
        await setProductState(
          {
            [StateType.collect]: CollectState.success,
          },
          appConfig.productStateFilename,
          skuIdInfoDirectoryHandle,
        );
        addMessage({
          category: skuIdInfo,
          type: OperationMessageType.success,
          message: `采集产品成功 ${doneMessage}`,
        });
        toast.success(`${skuIdInfo}: 采集成功`);

        collectingProduct[skuIdInfo] = false;
      } catch (error) {
        // 创建采集失败的状态
        await setProductState(
          {
            [StateType.collect]: CollectState.error,
            collectErrorMessage: (error as Error).message,
          },
          appConfig.productStateFilename,
          skuIdInfoDirectoryHandle,
        );

        addMessage({
          category: skuIdInfo,
          type: OperationMessageType.error,
          message: `采集产品失败: ${(error as Error).message}`,
        });
        // toast.error(`${skuIdInfo}: 采集产品失败: ${(error as Error).message}}`);
        collectingProduct[skuIdInfo] = false;
      }
    },
    [
      getAndSaveGigaDetailResource,
      getAndSaveGigaProductInfo,
      createSkuIdInfoDirectoryHandle,
      minAvailable,
    ],
  );

  return {
    getAndSaveGigaDetailResource,
    getAndSaveGigaProductInfo,
    collectGigaProduct,
  };
}
